/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.vdl.websort.server.entity.contextmodels;

import by.vdl.websort.server.entity.CategoryDTO;
import by.vdl.websort.server.entity.ItemDTO;
import by.vdl.websort.server.entity.SortedTableDTO;
import by.vdl.websort.server.entity.StudyDTO;

import java.util.*;

/**
 *
 * @author zeor
 */
public class StudyUnsortedModel {
    
    private StudyDTO study;
    private List<CategoryDTO> categories;
    private List<ItemDTO> items;
    private List<SortedTableDTO> sortedTable;

    public StudyUnsortedModel() {
        this.categories = new ArrayList<CategoryDTO>();
        this.items = new ArrayList<ItemDTO>();
        this.sortedTable = new ArrayList<SortedTableDTO>();
    }
    
    public StudyUnsortedModel(StudyDTO study, List<CategoryDTO> categories, List<ItemDTO> items, List<SortedTableDTO> sortedTable) {
        this.study = study;
        this.categories = categories;
        this.items = items;
        this.sortedTable = sortedTable;
    }

    public StudyDTO getStudy() {
        return study;
    }

    public void setStudy(StudyDTO study) {
        this.study = study;
    }
    
    public List<CategoryDTO> getCategories() {
        return categories;
    }

    public void setCategories(List<CategoryDTO> categories) {
        this.categories = categories;
    }

    public List<ItemDTO> getItems() {
        return items;
    }

    public void setItems(List<ItemDTO> items) {
        this.items = items;
    }

    public List<SortedTableDTO> getSortedTable() {
        return sortedTable;
    }

    public void setSortedTable(List<SortedTableDTO> sortedTable) {
        this.sortedTable = sortedTable;
    }
    
    public StudySortedModel sortStudy() {
        StudySortedModel studySortedModel = new StudySortedModel(study, new HashMap<CategoryDTO, Set<ItemDTO>>());
        
        for (SortedTableDTO sortedTie : sortedTable) {
            ItemDTO itemDTO = getItemById(sortedTie.getItemId());
            CategoryDTO categoryDTO = getCategoryById(sortedTie.getCategoryId());
            try {
                studySortedModel.getSortedStudy().get(categoryDTO).add(itemDTO);
            } catch (Exception e) {
                Set<ItemDTO> setItems = new HashSet<ItemDTO>(); 
                setItems.add(itemDTO);
                studySortedModel.getSortedStudy().put(categoryDTO, setItems);
            }
        }
        return studySortedModel;
    }
    
    private CategoryDTO getCategoryById(long categoryId){
        int position = categories.indexOf(new CategoryDTO(categoryId));
        return categories.get(position);
    }
    private ItemDTO getItemById(long itemId){
        int position = items.indexOf(new ItemDTO(itemId));
        return items.get(position);
    }
    
}
